<template>
  <el-upload class="upload-demo" ref="upload" list-type="picture-card" :action="upload_url" :headers="upload_headers" :limit="uplaod_limit"
    :file-list="file_list" :on-success="upload_success" :on-remove="upload_remove" :before-upload="beforeUpload" multiple>
    <i slot="default" class="el-icon-plus"></i>
    <div slot="file" slot-scope="{file}">
      <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
      <span class="el-upload-list__item-actions">
        <span class="el-upload-list__item-preview" @click="upload_preview(file)">
          <i class="el-icon-zoom-in"></i>
        </span>
        <span class="el-upload-list__item-delete" @click="upload_remove(file)">
          <i class="el-icon-delete"></i>
        </span>
      </span>
    </div>
    <!-- <el-button slot="trigger" size="small" type="primary">选取文件</el-button> -->
    <div class="el-upload__tip" slot="tip">只能上传jpg/png文件（最多{{uplaod_limit}}张），且不超过2MB</div>
  </el-upload>
</template>

<script>
  import { cloneDeep } from 'lodash'
  import { getUploadUrl } from '@/api/upload.js'
  import { getToken } from '@/utils/auth'

  export default {
    props: {
      fileListProp: {
        type: Array,
        default: []
      },
      uplaodLimitProp: {
      	type: Number,
      	default: 5
      },
    },
    watch: {
      'fileListProp': {
        handler(n, o) {
          this.clearFiles()
          this.file_list = cloneDeep(n);
        }
      },
      'uplaodLimitProp': {
        handler(n, o) {
          this.uplaod_limit = n;
        }
      }
    },
    data() {
      return {
        upload_url: getUploadUrl(),
        upload_headers: {},
        file_list: [],
        uplaod_limit: 5
      }
    },
    created() {
      this.upload_headers = {
        Authorization: getToken()
      }
    },
    methods: {
      upload_success(response, file, fileList) {
        this.$emit('upload-success', this.$refs.upload.uploadFiles);
      },
      upload_remove(file){
        let fileList = this.$refs.upload.uploadFiles;
        let index = fileList.findIndex((fileItem) => {
          return fileItem.uid === file.uid;
        });
        fileList.splice(index, 1);
        this.$emit('upload-remove', fileList);
      },
      upload_preview(file){
        this.$emit('upload-preview', file);
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG && !isPNG) {
          this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
          return false;
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return false;
        }
        return true;
      },
      // 清空上传列表
      clearFiles() {
        this.$refs.upload.clearFiles()
      },
    },
  }
</script>

<style>
  .upload-demo {
    width: 360px;
    margin: 10px 20px;
  }
</style>
